

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.jui.core.dynamic.DynamicEngine;

public class DynaRunTest {
    public static void main(String[] args) throws Exception {
        for (int i=1;i<1000;i++){
         	System.out.println("Hello world!");  
        } 
        
        String fullName = "DynaClass";
        StringBuilder src = new StringBuilder();
        src.append("public class DynaClass  {\n");
        src.append("    public static void main(String[] args) throws Exception {\n");
        src.append("         for (int i=1;i<100;i++){ \n");
        src.append("         	System.out.println(\"Hello world!\");  \n");
        src.append("         }  \n");
        src.append("   }\n");
        src.append("}\n");
 
        System.out.println(src);
        String message=null;
        PrintStream oldConsoleOut=null;
  		try {
          DynamicEngine de = DynamicEngine.getInstance();
          Object instance =  de.javaCodeToObject(fullName,src.toString());
	      Method mainMethod = instance.getClass().getMethod("main",String[].class);
	      
	      //得到控制台输出
	      ByteArrayOutputStream baoStream = new ByteArrayOutputStream(1024);
	      // cache stream
	      PrintStream cacheStream = new PrintStream(baoStream);
	      // old stream
	      // PrintStream oldStream = System.out;
	      oldConsoleOut=System.out;
	      System.setOut(cacheStream);
	       
	      //触发main方法
	      mainMethod.invoke(instance, (Object) new String[] { });
	      
	      
	      message = baoStream.toString();
	        
  		} catch (IllegalAccessException e) {
  			// TODO Auto-generated catch block
  			e.printStackTrace();
  		} catch (InstantiationException e) {
  			// TODO Auto-generated catch block
  			e.printStackTrace();
  		} catch (IllegalArgumentException e) {
  			// TODO Auto-generated catch block
  			e.printStackTrace();
  		} catch (InvocationTargetException e) {
  			// TODO Auto-generated catch block
  			e.printStackTrace();
  		} catch (NoSuchMethodException e) {
  			// TODO Auto-generated catch block
  			e.printStackTrace();
  		} catch (SecurityException e) {
  			// TODO Auto-generated catch block
  			e.printStackTrace();
  		}finally{
  			 System.setOut(oldConsoleOut);
  		}
  		System.out.println(message);
    
    }
}